package io.github.lee.jel.ui.folder

import android.app.Application
import com.chad.library.adapter4.BaseQuickAdapter
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.core.vm.BaseRefreshViewModel
import io.github.lee.core.vm.err.DataParseFailedException
import io.github.lee.core.vm.err.NoMoreDataException
import io.github.lee.jel.domain.Item
import io.github.lee.jel.err.ResponseFailException
import io.github.lee.jel.repository.JellyfinSessionRepository
import io.github.lee.jel.repository.UserRepository
import javax.inject.Inject

@HiltViewModel
class MediaFolderVM @Inject constructor(
    application: Application,
    private val repo: UserRepository,
    private val sessionRepo: JellyfinSessionRepository
) : BaseRefreshViewModel<Item>(application) {
    var sessionId: String? = ""
    override fun onCreateAdapter(): BaseQuickAdapter<Item, *> =
        MediaFolderAdapter(sessionRepo.queryCurrentSession())


    override fun onRefreshOrLoadMore(isRefresh: Boolean) {
        super.onRefreshOrLoadMore(isRefresh)
        launchResult(
            block = { repo.views(sessionId) },
            error = {
                it?.printStackTrace()
                error(it)
            }
        ) {
            if (!it.isSuccess) {
                error(ResponseFailException(it))
                return@launchResult
            }
            val data = it.data
            if (null == data) {
                error(DataParseFailedException(getApplication()))
                return@launchResult
            }
            val items = data.items
            if (items.isNullOrEmpty()) {
                empty(NoMoreDataException(getApplication()))
                return@launchResult
            }
            submitList(items)
            refreshSuccess()
        }


    }

}